import Config from './config.js'
import Util from './util.js'
import siteConfig from './siteConfig.js';

// 获取应用类型和名称的函数
function getAppInfo() {
    let app_type, app_type_name;
    // #ifdef H5
    app_type = 'h5';
    app_type_name = 'H5';
    // #endif

    // #ifdef MP-WEIXIN
    app_type = 'weapp';
    app_type_name = '微信小程序';
    // #endif

    // #ifdef APP-PLUS
    app_type = '1';
    app_type_name = 'PDA小程序版';
    // #endif
    return { app_type, app_type_name };
}

// 检查配置是否存在
function checkConfig(configUrl, message) {
    if (!configUrl) {
        uni.showToast({
            title: message,
            'icon': 'none',
            duration: 10000
        });
        return false;
    }
    return true;
}

// 处理请求错误
function handleRequestError(res, configUrl) {
    uni.hideLoading();
    if (res.errMsg && res.errMsg == 'request:fail url not in domain list') {
        uni.showToast({
            title: configUrl + '不在request 合法域名列表中',
            'icon': 'none',
            duration: 10000
        });
    } else if ((res.errMsg && res.errMsg != "request:ok") || (res.statusCode && [200, 500].indexOf(res.statusCode) == -1)) {
        uni.showToast({
            title: configUrl + '请求失败',
            'icon': 'none',
            duration: 10000
        });
    }
}

// 处理401状态码
function handle401(role) {
    switch (role) {
        case 'dealer':
            uni.removeStorageSync('token');
            uni.removeStorageSync('dealer_info');
            uni.redirectTo({
                url: "/agentSystem/pages/login"
            });
            break;
        case 'api':
            uni.removeStorageSync('lrusertoken');
            break;
        case 'pda':
            uni.removeStorageSync('pdatoken');
            uni.reLaunch({
                url: "/PDA/pages/login"
            });
            break;
    }
}

// 公共的发送请求方法
function commonSendRequest(role, params, baseUrl, tokenKey) {
    if (!checkConfig(baseUrl, '未配置请求域名')) {
        return;
    }
    const token = uni.getStorageSync(tokenKey) || '';
    params.header[`lr-${role}-token`] = token;
    params.baseUrl = baseUrl + params.url;
    return this.sendRequest(role, params);
}

export default {
    async getUserInfo() {
        const dealer_info = uni.getStorageSync('dealer_info');
        if (dealer_info) {
            // return dealer_info;
        }
        const res = await this.sendRequest({
            url: 'Index/getuser'
        });
        if (res.code === 1) {
            uni.setStorageSync('dealer_info', res.data);
            return res.data;
        } else {
            uni.removeStorageSync('token');
            uni.removeStorageSync('dealer_info');
            uni.reLaunch({
                url: "/pages/login/login"
            });
        }
    },

    sendDealerRequest(params) {
        return commonSendRequest.call(this, 'dealer', params, Config.baseUrl, 'token');
    },

    sendPdaRequest(params) {
        return commonSendRequest.call(this, 'pda', params, Config.basePdaUrl, 'pdatoken');
    },

    sendApiRequest(params) {
        return commonSendRequest.call(this, 'api', params, Config.baseApiUrl, 'lrusertoken');
    },

    sendSalesmanRequest(params) {
        return commonSendRequest.call(this, 'salesman', params, Config.baseSalesmanUrl, 'lrsalesmantoken');
    },

    sendRequest(role, params) {
        const { app_type, app_type_name } = getAppInfo();
        const isNonLoading = params.isNonLoading ? params.isNonLoading : false;
        if (!isNonLoading) {
            uni.showLoading({
                title: '加载中',
                mask: true
            });
        }
        const method = params.data != undefined ? 'POST' : 'GET';
        const url = params.baseUrl;
        const data = {
            app_type,
            app_type_name
        };
        let header = params.header;
        if (!header) {
            header = {};
        }
        header['content-type'] = 'application/json';
        params.async = false;

        if (params.data != undefined) Object.assign(data, params.data);

        if (params.async === false) {
            return new Promise((resolve, reject) => {
                uni.request({
                    url: url,
                    method: method,
                    data: data,
                    header: header,
                    dataType: params.dataType || 'json',
                    responseType: params.responseType || 'text',
                    success: (res) => {
                        uni.hideLoading();
                        if (res.data.code == 401) {
                            handle401(role);
                        }
                        resolve(res.data);
                    },
                    fail: (res) => {
                        handleRequestError(res, Config.baseUrl);
                        reject(res);
                    },
                    complete: (res) => {
                        handleRequestError(res, Config.baseUrl);
                        reject(res.data);
                    }
                });
            });
        } else {
            uni.request({
                url: url,
                method: method,
                data: data,
                header: header,
                dataType: params.dataType || 'json',
                responseType: params.responseType || 'text',
                success: (res) => {
                    uni.hideLoading();
                    if (res.data.code == 401) {
                        handle401(role);
                    }
                    typeof params.success == 'function' && params.success(res.data);
                },
                fail: (res) => {
                    handleRequestError(res, Config.baseUrl);
                    typeof params.fail == 'function' && params.fail(res);
                },
                complete: (res) => {
                    handleRequestError(res, Config.baseUrl);
                    typeof params.complete == 'function' && params.complete(res.data);
                }
            });
        }
    },

    upload(params) {
        const { app_type, app_type_name } = getAppInfo();
        uni.showLoading({
            title: '上传中...',
            mask: true
        });
        uni.uploadFile({
            url: Config.baseUrl + params.url + '?driver=' + siteConfig.upload.mode,
            filePath: params.filePath,
            name: params.name || 'file',
            fileType: params.fileType || 'image',
            formData: {
                app_type,
                app_type_name,
            },
            header: {
                'lr-dealer-token': uni.getStorageSync('token')
            },
            success: (res) => {
                uni.hideLoading();
                typeof params.success == 'function' && params.success(JSON.parse(res.data));
            },
            fail: (res) => {
                uni.hideLoading();
                typeof params.fail == 'function' && params.fail(res);
            }
        });
    }
};